package com.stadium.tools;

import java.util.concurrent.atomic.AtomicInteger;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;

/*
 * 限制登录次数，如果出错5次，锁定1个小时
 */
public class LimitRentryHashedMatcher extends HashedCredentialsMatcher {

	@Override
	public boolean doCredentialsMatch(AuthenticationToken token,
			AuthenticationInfo info) {
		
		String account = (String) token.getPrincipal();
		//获取账号登录次数
		Object element = EhcacheUtil.getItem(account);
		if (element == null) {
			EhcacheUtil.putItem(account, 1);
			element = 0;
		} else {
			int count = Integer.valueOf(element.toString()) + 1;
			element = count;
			EhcacheUtil.putItem(account, element);
		}

		AtomicInteger retryCount = new AtomicInteger(Integer.valueOf(element
				.toString()));
		//判断账号登录次数
		if(retryCount.incrementAndGet() > 5){
			throw new ExcessiveAttemptsException();
		}
		//判断是否登录成功
		boolean matches =  super.doCredentialsMatch(token, info);
		//登录成功，移除登录次数
		if(matches){
			EhcacheUtil.removeItem(account);
		}
		return matches;
	}

}
